package com.psmorandi.peschampweb.android.tab;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.psmorandi.peschampweb.android.model.Partida;
import com.psmorandi.peschampweb.android.tab.listeners.OnPartidaSelecionaListener;

@SuppressLint("ValidFragment")
public class SelecionaPartidasFragment extends ListFragment {

	private OnPartidaSelecionaListener mCallback;
	private List<Partida> mPartidas;

	public SelecionaPartidasFragment() {

	}

	public SelecionaPartidasFragment(List<Partida> _partidas) {
		mPartidas = _partidas;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// We need to use a different list item layout for devices older than
		// Honeycomb
		int layout = android.R.layout.simple_list_item_activated_1;

		// Gerando a lista de partidas:
		String[] lst = new String[mPartidas.size()];
		SimpleDateFormat formatadorData = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
		int i = 0;
		for (Partida partida : mPartidas) {
			String texto = formatadorData.format(partida.getData()) + " - " + partida.getJogador1().getNome() + " (" + partida.getJogador1().getTimeEscolhido()
					+ ") x " + partida.getJogador2().getNome() + " (" + partida.getJogador2().getTimeEscolhido() + ")";
			lst[i++] = texto;
		}

		// Create an array adapter for the list view, using the Ipsum headlines
		// array
		setListAdapter(new ArrayAdapter<String>(getActivity(), layout, lst));
	}

	@Override
	public void onStart() {
		super.onStart();
		getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		// This makes sure that the container activity has implemented
		// the callback interface. If not, it throws an exception.
		try {
			mCallback = (OnPartidaSelecionaListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString() + " must implement OnPartidaSelecionaListener");
		}
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		getListView().setItemChecked(position, true);
		mCallback.onPartidaSelecionada(mPartidas.get(position));
		// Set the item as checked to be highlighted when in two-pane layout
	}

}
